package bizsocket.ohos;

import bizsocket.core.AbstractBizSocket;
import bizsocket.core.AbstractFragmentRequestQueue;
import bizsocket.tcp.Packet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * OhosFragmentRequestQueue
 *
 * @since 2021-05-06
 */
public abstract class OhosFragmentRequestQueue<T extends Packet> extends AbstractFragmentRequestQueue<T> {
    private final EventRunner runner;
    private final EventHandler handler;

    public OhosFragmentRequestQueue(AbstractBizSocket bizSocket) {
        super(bizSocket);
        runner = EventRunner.getMainEventRunner();
        handler = new EventHandler(runner);
    }

    @Override
    public void dispatchPacket(final Packet responsePacket) {
        if (handler.getEventRunner().getThreadId() == Thread.currentThread().getId()) {
            OhosFragmentRequestQueue.super.dispatchPacket(responsePacket);
        } else {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    OhosFragmentRequestQueue.super.dispatchPacket(responsePacket);
                }
            };
            Util.runInMainThread(runnable);
        }
    }
}
